<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\admin\model\Project as ProjectModel;
use think\Db;
use Exception;
use fast\Tree;
use app\admin\model\AdminDepart;
use app\admin\model\AuthGroup;
use fast\Date;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx as Wxlsx;

/**
 * 项目管理
 *
 * @icon fa fa-user
 */
class Project extends Backend
{

    protected $searchFields = 'id,name';
	protected $noNeedRight = ['departlist'];
	
    /**
     * @var \app\admin\model\Project
     */
    protected $model = null;
	protected $relationSearch = true;
	protected $departdata = [];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Project');
		$this->paymentModel = model('ProjectPayment');
		
		$departList = collection(AdminDepart::column('id,pid,name'))->toArray();
        Tree::instance()->init($departList);
        $departList = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
		
        $departName = [];
        foreach ($departList as $k => $v) {
            $departName[$v['id']] = $v['name'];
        }
        $this->departdata = $departName;
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
			
			$filter = json_decode($this->request->get("filter"),true);
			$op = json_decode($this->request->get("op"),true);

			$filter_paymenttime = '';
			if(isset($filter['paymenttime'])){
				$filter_paymenttime = $filter['paymenttime'];
				unset($filter['paymenttime'],$op['paymenttime']);
				$this->request->get(["filter"=>json_encode($filter),'op'=>json_encode($op)]);
			}
			
			if(isset($filter['budgetyear'])){
				$year = $filter['budgetyear'];
			}else{
				$year = date('Y');
			}

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            
            $map = [];
			$groupIds = $this->auth->getGroupIds();
			$groupPid = AuthGroup::where('id', $groupIds[0])->value('pid');
			if($groupPid != 0 && $groupPid != 1)
			{
				$map['nm_project.procuredepart'] = $this->auth->depart_id;
			}
			
			$type = $this->request->param('type');
			if($type == 1)
			{
				$paymenttime = [strtotime(date('Y-m-d').' 00:00:00'), strtotime(date('Y-m-d').' 23:59:59')];
			}
			elseif($type == 2)
			{
				$starttime = Date::unixtime('day', 0);
				$endtime = Date::unixtime('day', 15, 'end');
				$paymenttime = [$starttime, $endtime];
			}
			
            $list = $this->model
				->with(['payments'=>function($q){
					$q->where('paymentstatus', 1)->order('paymenttime','desc');
				}, 'admin', 'depart'])
				->where($map);
			if($filter_paymenttime)
			{
				$filter_paymenttime = explode(' - ', $filter_paymenttime);
				$filter_paymenttime = [strtotime($filter_paymenttime[0]), strtotime($filter_paymenttime[1])];
				$list = $list->join('nm_project_payment','nm_project_payment.project_id = nm_project.id')
							->where('nm_project_payment.paymenttime','BETWEEN TIME',$filter_paymenttime)
							->group('project.id');
			}
			elseif($type == 1 || $type == 2)
			{
				$list = $list->join('nm_project_payment','nm_project_payment.project_id = nm_project.id')
							->where('nm_project_payment.paymenttime','BETWEEN TIME',$paymenttime)
							->where('nm_project_payment.paymentstatus', 0)
							->group('project.id');
			}
			
            $list = $list->where($where)
                ->order($sort, $order)
                ->paginate($limit);

			foreach($list as &$vo)
			{
				//执行比例
				$leiji_paymentmoney = 0;
				foreach($vo['payments'] as $value)
				{
					if($value['paymentmoney'])
					{
						$leiji_paymentmoney += $value['paymentmoney'];
					}
				}
				$vo['execute_rate'] = ($vo['biddermoney']!=0?round($leiji_paymentmoney*100/$vo['biddermoney'], 2):0).'%';	
			}
			
            $result = array("total" => $list->total(), "rows" => $list->items(), "year" => $year);
			
            return json($result);
        }
		
		$year = intval($this->request->param('year'));
		$type = intval($this->request->param('type'));
		//今日代办项目数和15代办项目数没有预算年度限制
		if(!$year && $type != 1 && $type != 2)
		{
			$year = date('Y');
		}
		$this->assignconfig('year', $year);//这个有必要，因为今日代办项目数和15代办项目数不能有预算年度限制
        return $this->view->fetch();
    }
	
	public function implementing()
    {
		//设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
			$filter = json_decode($this->request->get("filter"),true);
			$op = json_decode($this->request->get("op"),true);
			
			if(isset($filter['budgetyear'])){
				$year = $filter['budgetyear'];
			}else{
				$year = date('Y');
			}

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            
            $map = [];
			$groupIds = $this->auth->getGroupIds();
			$groupPid = AuthGroup::where('id', $groupIds[0])->value('pid');
			if($groupPid != 0 && $groupPid != 1)
			{
				$map['procuredepart'] = $this->auth->depart_id;
			}
			
			$map['status'] = 2;
			
            $list = $this->model->with(['payments'=>function($q){
					$q->where('paymentstatus', 1)->order('paymenttime','desc');
				}])->where($map)->where($where)->order($sort, $order)->paginate($limit);
			foreach($list as &$vo)
			{
				//执行比例
				$leiji_paymentmoney = 0;
				foreach($vo['payments'] as $value)
				{
					if($value['paymentmoney'])
					{
						$leiji_paymentmoney += $value['paymentmoney'];
					}
				}
				$vo['payedmoney'] = $leiji_paymentmoney;
				$vo['execute_rate'] = ($vo['biddermoney']!=0?round($leiji_paymentmoney*100/$vo['biddermoney'], 2):0).'%';	
			}
            $result = array("total" => $list->total(), "rows" => $list->items(), "year" => $year);
			
            return json($result);
		}
		
		$year = intval($this->request->param('year'));
		if(!$year)
		{
			$year = date('Y');
		}
		$this->assignconfig('year', $year);
		return $this->view->fetch();
	}
	
	public function buying()
	{
		//设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
			$filter = json_decode($this->request->get("filter"),true);
			$op = json_decode($this->request->get("op"),true);
			
			$year = '';
			if(isset($filter['budgetyear'])){
				$year = $filter['budgetyear'];
			}else{
				$year = date('Y');
			}

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            
            $map = [];
			$groupIds = $this->auth->getGroupIds();
			$groupPid = AuthGroup::where('id', $groupIds[0])->value('pid');
			if($groupPid != 0 && $groupPid != 1)
			{
				$map['procuredepart'] = $this->auth->depart_id;
			}
			
			//$map['status'] = 1;
			
            $list = $this->model->where($map)->where($where)
					->where(function($query){
						$query->where('procuretype', 0)->whereOr(function($query){
							$query->where('procuretype', 7)->where(function($query){
								$query->where('biddercompany', '')->whereOr('contracttime', 0);
							});
						})->whereOr(function($query){
							$query->where('procuretype', '<>', 7)->where(function($query){
								$query->where('agentcompany', '')->whereOr('noticetime', 0)->whereOr('bidopentime', 0)->whereOr(function($query){
									$query->where('bidding', '')->where('nobidding', 0);
								})->whereOr(function($query){
									$query->where('rfp', '')->where('norfp', 0);
								})->whereOr(function($query){
									$query->where('acceptance', '')->where('noacceptance', 0);
								})->whereOr(function($query){
									$query->where('lawyerletter', '')->where('nolawyerletter', 0);
								})->whereOr(function($query){
									$query->where('contract', '')->where('nocontract', 0);
								});
							});
						});
					})
					->order($sort, $order)->paginate($limit);
			
            $result = array("total" => $list->total(), "rows" => $list->items(), "year" => $year);
			
            return json($result);
		}
		
		$year = intval($this->request->param('year'));
		if(!$year)
		{
			$year = date('Y');
		}
		$this->assignconfig('year', $year);
		return $this->view->fetch();
	}
	
	/* public function export()
	{
		try{
			$spreadsheet = new Spreadsheet();
			$sheet = $spreadsheet->getActiveSheet();
			$sheet->getStyle('A1:S1')->getFont()->setBold(true);
			$sheet->getCell('A1')->setValue('序号');
			$sheet->getCell('B1')->setValue('项目名称');
			$sheet->getCell('C1')->setValue('开始时间');
			$sheet->getCell('D1')->setValue('结束时间');
			$sheet->getCell('E1')->setValue('采购科室');
			$sheet->getCell('F1')->setValue('采购方式');
			$sheet->getCell('G1')->setValue('中标公司');
			$sheet->getCell('H1')->setValue('代理公司');
			$sheet->getCell('I1')->setValue('投标文件');
			$sheet->getCell('J1')->setValue('竞标书');
			$sheet->getCell('K1')->setValue('中标合同');
			$sheet->getCell('L1')->setValue('律师意见函');
			$sheet->getCell('M1')->setValue('联系人');
			$sheet->getCell('N1')->setValue('联系方式');
			$sheet->getCell('O1')->setValue('项目金额');
			$sheet->getCell('P1')->setValue('中标金额');
			$sheet->getCell('Q1')->setValue('支付次数');
			$sheet->getCell('R1')->setValue('验收报告');
			$sheet->getCell('S1')->setValue('完成情况');
			
			$list = $this->model->with(['payments'=>function($q){
					$q->order('id','asc');
				}, 'admin', 'depart'])->order('id desc')->select();
			$i = 2;
			foreach($list as $key=>$vo)
			{
				$sheet->getRowDimension($i)->setRowHeight(30);
				$sheet->setCellValueByColumnAndRow(1, $i, $key+1);
				$sheet->setCellValueByColumnAndRow(2, $i, $vo['name']);
				$sheet->setCellValueByColumnAndRow(3, $i, date('Y-m-d', $vo['starttime']));
				$sheet->setCellValueByColumnAndRow(4, $i, date('Y-m-d', $vo['endtime']));
				$sheet->setCellValueByColumnAndRow(5, $i, $vo['depart']['name']);
				$sheet->setCellValueByColumnAndRow(6, $i, $vo['procuretype']==1?'招标采购':($vo['procuretype']==2?'非招标采购':'集中采购'));
				$sheet->setCellValueByColumnAndRow(7, $i, $vo['biddercompany']);
				$sheet->setCellValueByColumnAndRow(8, $i, $vo['agentcompany']);
				$sheet->setCellValueByColumnAndRow(9, $i, $vo['rfp']?'附件':'');
				if($vo['rfp']) $sheet->getCellByColumnAndRow(9, $i)->getHyperlink()->setUrl($_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].$vo['rfp']);
				$sheet->setCellValueByColumnAndRow(10, $i, $vo['bidding']?'附件':'');
				if($vo['bidding']) $sheet->getCellByColumnAndRow(10, $i)->getHyperlink()->setUrl($_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].$vo['bidding']);
				$sheet->setCellValueByColumnAndRow(11, $i, $vo['contract']?'附件':'');
				if($vo['contract']) $sheet->getCellByColumnAndRow(11, $i)->getHyperlink()->setUrl($_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].$vo['contract']);
				$sheet->setCellValueByColumnAndRow(12, $i, $vo['lawyerletter']?'附件':'');
				if($vo['lawyerletter']) $sheet->getCellByColumnAndRow(12, $i)->getHyperlink()->setUrl($_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].$vo['lawyerletter']);
				$sheet->setCellValueByColumnAndRow(13, $i, $vo['contacter']);
				$sheet->setCellValueByColumnAndRow(14, $i, $vo['contactphone']);
				$sheet->setCellValueByColumnAndRow(15, $i, $vo['totalmoney']);
				$sheet->setCellValueByColumnAndRow(16, $i, $vo['biddermoney']);
				$sheet->setCellValueByColumnAndRow(17, $i, $vo['paymenttimes']);
				$sheet->setCellValueByColumnAndRow(18, $i, $vo['checkreport']?'附件':'');
				if($vo['checkreport']) $sheet->getCellByColumnAndRow(18, $i)->getHyperlink()->setUrl($_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].$vo['checkreport']);
				$sheet->setCellValueByColumnAndRow(19, $i, $vo['checkstatus']==1?'完成':'未完成');
				
				if($vo['payments'])
				{
					$sheet->getStyle('B'.($i+1).':G'.($i+1))->getFont()->setBold(true);
					$sheet->getCellByColumnAndRow(2, $i+1)->setValue('序号');
					$sheet->getCellByColumnAndRow(3, $i+1)->setValue('支付时间');
					$sheet->getCellByColumnAndRow(4, $i+1)->setValue('支付金额');
					$sheet->getCellByColumnAndRow(5, $i+1)->setValue('是否付款');
					$sheet->getCellByColumnAndRow(6, $i+1)->setValue('支付比例');
					$sheet->getCellByColumnAndRow(7, $i+1)->setValue('支付条件');
					foreach($vo['payments'] as $key2=>$vo2)
					{
						$sheet->setCellValueByColumnAndRow(2, $i+2+$key2, '第'.($key2+1).'次付款');
						$sheet->setCellValueByColumnAndRow(3, $i+2+$key2, date('Y-m-d', $vo2['paymenttime']));
						$sheet->setCellValueByColumnAndRow(4, $i+2+$key2, $vo2['paymentmoney']);
						$sheet->setCellValueByColumnAndRow(5, $i+2+$key2, $vo2['paymentstatus']==1?'已支付':'未支付');
						$sheet->setCellValueByColumnAndRow(6, $i+2+$key2, round($vo2['paymentmoney']*100/$vo['biddermoney'], 2).'%');
						$sheet->setCellValueByColumnAndRow(7, $i+2+$key2, $vo2['paymentcondition']);
					}
					
					$i = $i+count($vo['payments'])+2;
				}
			}
			
			$filename = '项目列表';
			// MIME 协议，文件的类型，不设置，会默认html
			header('Content-Type:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
			// MIME 协议的扩展
			header('Content-Disposition:attachment;filename='.$filename.'.xlsx');
			// 缓存控制
			header('Cache-Control:max-age=0');
			
			$writer = new Wxlsx($spreadsheet);
			$writer->save('php://output');
		} catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
	} */
	
	public function export()
	{
		try{
			$filter = json_decode($this->request->get("filter"),true);
			$op = json_decode($this->request->get("op"),true);

			if(isset($filter['paymenttime'])){
				unset($filter['paymenttime'],$op['paymenttime']);
				$this->request->get(["filter"=>json_encode($filter),'op'=>json_encode($op)]);
			}
			
			if(isset($filter['budgetyear'])){
				$year = $filter['budgetyear'];
			}else{
				$year = date('Y');
			}
			
			$template = 'project_template.xlsx';
			$filePath = ROOT_PATH . DS . 'public' . DS . $template;
			if (!is_file($filePath)) {
				$this->error(__('No file were found'));
			}
			
			$reader = new Xlsx();
			if (!$spreadsheet = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
			
			$sheet = $spreadsheet->getActiveSheet()->setTitle($year.'采购项目');
			$sheet->setCellValueByColumnAndRow(1, 1, $year.'年政府采购项目统计表');
			$sheet->setCellValueByColumnAndRow(12, 2, date('Y年m月d日'));
			
			list($where, $sort, $order) = $this->buildparams();
			
			$map = [];
			$groupIds = $this->auth->getGroupIds();
			if($groupIds[0] == 3)
			{
				$map['nm_project.procuredepart'] = $this->auth->depart_id;
			}
			
			$list = $this->model->with(['payments'=>function($q){
					$q->where('paymentstatus', 1);
				}, 'admin', 'depart'])->where($where)->where($map)->order($sort, $order)->select();
			foreach($list as $key=>$vo)
			{
				$row = $key+5;
				//$sheet->getRowDimension($key+2)->setRowHeight(25);
				if($vo['status'] != 3)
				{
					$sheet->getStyle('A'.$row.':AM'.$row)->getFont()->getColor()->setRGB('CD2626');
				}
				
				//执行比例
				$leiji_paymentmoney = 0;
				foreach($vo['payments'] as $value)
				{
					if($value['paymentmoney'])
					{
						$leiji_paymentmoney += $value['paymentmoney'];
					}
				}
				$vo['execute_rate'] = ($vo['biddermoney']!=0?round($leiji_paymentmoney*100/$vo['biddermoney'], 2):0).'%';			
				
				$sheet->setCellValueByColumnAndRow(1, $row, $vo['serialnumber']);
				//$sheet->setCellValueByColumnAndRow(2, $row, $vo['starttime']?date('Y年m月d日', $vo['starttime']):'');
				$sheet->setCellValueByColumnAndRow(2, $row, $vo['name']);
				$sheet->setCellValueByColumnAndRow(3, $row, $vo['depart']['name']);
				$sheet->setCellValueByColumnAndRow(4, $row, $vo['contacter']);
				$sheet->setCellValueByColumnAndRow(5, $row, $vo['contactphone']);
				$sheet->setCellValueByColumnAndRow(6, $row, getProcureType($vo['procuretype']));
				$sheet->setCellValueByColumnAndRow(7, $row, $vo['agentcompany']);
				$sheet->setCellValueByColumnAndRow(8, $row, $vo['noticetime']?date('Y年m月d日', $vo['noticetime']):'');
				$sheet->setCellValueByColumnAndRow(9, $row, $vo['bidopentime']?date('Y年m月d日', $vo['bidopentime']):'');
				$sheet->setCellValueByColumnAndRow(10, $row, $vo['biddercompany']);
				$sheet->setCellValueByColumnAndRow(11, $row, $vo['fundingsource']);
				$sheet->setCellValueByColumnAndRow(12, $row, $vo['totalmoney']);
				$sheet->setCellValueByColumnAndRow(13, $row, $vo['biddermoney']);
				$sheet->setCellValueByColumnAndRow(14, $row, $vo['lawyerletter']?'附件':'');
				if($vo['lawyerletter']) $sheet->getCellByColumnAndRow(14, $row)->getHyperlink()->setUrl($_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].$vo['lawyerletter']);
				$sheet->setCellValueByColumnAndRow(15, $row, $vo['contracttime']?date('Y年m月d日', $vo['contracttime']):'');
				$sheet->setCellValueByColumnAndRow(16, $row, $vo['endtime']?date('Y年m月d日', $vo['endtime']):'');
				$sheet->setCellValueByColumnAndRow(17, $row, '');
				$sheet->setCellValueByColumnAndRow(18, $row, $vo['execute_rate']);
				
				$payments = $this->paymentModel->where('project_id', $vo['id'])->limit(3)->order('id', 'asc')->select();
				if(isset($payments[0]))
				{			
					$sheet->setCellValueByColumnAndRow(19, $row, ($vo['biddermoney']!=0?round($payments[0]['paymentmoney']*100/$vo['biddermoney'], 2):0).'%');
					$sheet->setCellValueByColumnAndRow(20, $row, $payments[0]['paymentmoney']);
					$sheet->setCellValueByColumnAndRow(21, $row, $payments[0]['paymenttime']?date('Y年m月d日', $payments[0]['paymenttime']):'');
					$sheet->setCellValueByColumnAndRow(22, $row, $payments[0]['realpaymenttime']?date('Y年m月d日', $payments[0]['realpaymenttime']):'');
					$sheet->setCellValueByColumnAndRow(23, $row, $payments[0]['paymentcondition']);
				}
				if(isset($payments[1]))
				{
					$sheet->setCellValueByColumnAndRow(24, $row, ($vo['biddermoney']!=0?round($payments[1]['paymentmoney']*100/$vo['biddermoney'], 2):0).'%');
					$sheet->setCellValueByColumnAndRow(25, $row, $payments[1]['paymentmoney']);
					$sheet->setCellValueByColumnAndRow(26, $row, $payments[1]['paymenttime']?date('Y年m月d日', $payments[1]['paymenttime']):'');
					$sheet->setCellValueByColumnAndRow(27, $row, $payments[1]['realpaymenttime']?date('Y年m月d日', $payments[1]['realpaymenttime']):'');
					$sheet->setCellValueByColumnAndRow(28, $row, $payments[1]['paymentcondition']);
				}
				if(isset($payments[2]))
				{
					$sheet->setCellValueByColumnAndRow(29, $row, ($vo['biddermoney']!=0?round($payments[2]['paymentmoney']*100/$vo['biddermoney'], 2):0).'%');
					$sheet->setCellValueByColumnAndRow(30, $row, $payments[2]['paymentmoney']);
					$sheet->setCellValueByColumnAndRow(31, $row, $payments[2]['paymenttime']?date('Y年m月d日', $payments[2]['paymenttime']):'');
					$sheet->setCellValueByColumnAndRow(32, $row, $payments[2]['realpaymenttime']?date('Y年m月d日', $payments[2]['realpaymenttime']):'');
					$sheet->setCellValueByColumnAndRow(33, $row, $payments[2]['paymentcondition']);
				}
				
				$sheet->setCellValueByColumnAndRow(34, $row, $vo['warranty_period']);
				$sheet->setCellValueByColumnAndRow(35, $row, $vo['supervision_depart']);
				$sheet->setCellValueByColumnAndRow(36, $row, $vo['supervision_report']?'附件':'');
				if($vo['supervision_report']) $sheet->getCellByColumnAndRow(36, $row)->getHyperlink()->setUrl($_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].$vo['supervision_report']);
				$sheet->setCellValueByColumnAndRow(37, $row, $vo['audit_depart']);
				$sheet->setCellValueByColumnAndRow(38, $row, $vo['audit_report']?'附件':'');
				if($vo['audit_report']) $sheet->getCellByColumnAndRow(38, $row)->getHyperlink()->setUrl($_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].$vo['audit_report']);
				$sheet->setCellValueByColumnAndRow(39, $row, $vo['checkreport']?'附件':'');
				if($vo['checkreport']) $sheet->getCellByColumnAndRow(39, $row)->getHyperlink()->setUrl($_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].$vo['checkreport']);
			}
			
			$filename = $year.'采购项目';
			// MIME 协议，文件的类型，不设置，会默认html
			header('Content-Type:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
			// MIME 协议的扩展
			header('Content-Disposition:attachment;filename='.$filename.'.xlsx');
			// 缓存控制
			header('Cache-Control:max-age=0');
			
			$writer = new Wxlsx($spreadsheet);
			$writer->save('php://output');
		} catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
	}
	
	/* public function export()
	{
		try{
			$filter = json_decode($this->request->get("filter"),true);
			$op = json_decode($this->request->get("op"),true);

			if(isset($filter['paymenttime'])){
				unset($filter['paymenttime'],$op['paymenttime']);
				$this->request->get(["filter"=>json_encode($filter),'op'=>json_encode($op)]);
			}
			
			if(isset($filter['starttime'])){
				$starttime = $filter['starttime'];
				$starttime = explode('-', $starttime);
				$year = $starttime[0];
			}else{
				$year = date('Y');
			}
			
			$spreadsheet = new Spreadsheet();
			$sheet = $spreadsheet->getActiveSheet()->setTitle('项目列表');
			
			$sheet->mergeCells('A1:AJ1');
			$sheet->getRowDimension('1')->setRowHeight(30);
			$sheet->getStyleByColumnAndRow(1, 1)->applyFromArray(array('alignment' => array('horizontal' => 'center', 'vertical' => 'center')))->getFont()->setBold(true)->setSize(20);//设置颜色->setColor( new \PHPExcel_Style_Color( \PHPExcel_Style_Color::COLOR_DARKGREEN ) );设置斜体->setItalic( true);
			$sheet->setCellValueByColumnAndRow(1, 1, $year.'年政府采购项目统计表');
		
			$sheet->getStyle('A2:AJ2')->getFont()->setBold(true);
			$sheet->getCell('A2')->setValue('序号');
			$sheet->getCell('B2')->setValue('项目编号');
			$sheet->getCell('C2')->setValue('预算年度');
			$sheet->getCell('D2')->setValue('项目名称');
			$sheet->getCell('E2')->setValue('项目采购时间');
			$sheet->getCell('F2')->setValue('项目实施时间');
			$sheet->getCell('G2')->setValue('项目完成时间');
			$sheet->getCell('H2')->setValue('负责科室');
			$sheet->getCell('I2')->setValue('联系人');
			$sheet->getCell('J2')->setValue('联系方式');
			$sheet->getCell('K2')->setValue('采购方式');
			$sheet->getCell('L2')->setValue('代理公司');
			$sheet->getCell('M2')->setValue('中标单位');
			$sheet->getCell('N2')->setValue('公告发布时间');
			$sheet->getCell('O2')->setValue('开标时间');
			$sheet->getCell('P2')->setValue('合同签订时间');
			$sheet->getCell('Q2')->setValue('招标文件');
			$sheet->getCell('R2')->setValue('投标文件');
			$sheet->getCell('S2')->setValue('中标通知书');
			$sheet->getCell('T2')->setValue('律师审核意见书');
			$sheet->getCell('U2')->setValue('中标合同');
			$sheet->getCell('V2')->setValue('预算金额');
			$sheet->getCell('W2')->setValue('合同金额');
			$sheet->getCell('X2')->setValue('执行比例');
			$sheet->getCell('Y2')->setValue('付款次数');
			$sheet->getCell('Z2')->setValue('已付次数');
			$sheet->getCell('AA2')->setValue('资金来源');
			$sheet->getCell('AB2')->setValue('验收报告');
			$sheet->getCell('AC2')->setValue('验收时间');
			$sheet->getCell('AD2')->setValue('质保期限');
			$sheet->getCell('AE2')->setValue('监理单位');
			$sheet->getCell('AF2')->setValue('监理报告');
			$sheet->getCell('AG2')->setValue('工程审计单位');
			$sheet->getCell('AH2')->setValue('工程审计报告');
			$sheet->getCell('AI2')->setValue('项目进度');
			$sheet->getCell('AJ2')->setValue('录入人');
			
			list($where, $sort, $order) = $this->buildparams();
			
			$list = $this->model->with(['payments'=>function($q){
					$q->where('paymentstatus', 1);
				}, 'admin', 'depart'])->where($where)->order($sort, $order)->select();
			foreach($list as $key=>$vo)
			{
				$row = $key+3;
				//$sheet->getRowDimension($key+2)->setRowHeight(25);
				if($vo['status'] != 3)
				{
					$sheet->getStyle('A'.$row.':AJ'.$row)->getFont()->getColor()->setRGB('CD2626');
				}
				
				//执行比例
				$leiji_paymentmoney = 0;
				foreach($vo['payments'] as $value)
				{
					if($value['paymentmoney'])
					{
						$leiji_paymentmoney += $value['paymentmoney'];
					}
				}
				$vo['execute_rate'] = ($vo['biddermoney']!=0?round($leiji_paymentmoney*100/$vo['biddermoney'], 2):0).'%';			
				
				$sheet->setCellValueByColumnAndRow(1, $row, $key+1);
				$sheet->setCellValueByColumnAndRow(2, $row, $vo['serialnumber']);
				$sheet->setCellValueByColumnAndRow(3, $row, $vo['budgetyear']?date('Y', $vo['budgetyear']):'');
				$sheet->setCellValueByColumnAndRow(4, $row, $vo['name']);
				$sheet->setCellValueByColumnAndRow(5, $row, $vo['starttime']?date('Y-m-d', $vo['starttime']):'');
				$sheet->setCellValueByColumnAndRow(6, $row, $vo['shishitime']?date('Y-m-d', $vo['shishitime']):'');
				$sheet->setCellValueByColumnAndRow(7, $row, $vo['endtime']?date('Y-m-d', $vo['endtime']):'');
				$sheet->setCellValueByColumnAndRow(8, $row, $vo['depart']['name']);
				$sheet->setCellValueByColumnAndRow(9, $row, $vo['contacter']);
				$sheet->setCellValueByColumnAndRow(10, $row, $vo['contactphone']);
				$sheet->setCellValueByColumnAndRow(11, $row, getProcureType($vo['procuretype']));
				$sheet->setCellValueByColumnAndRow(12, $row, $vo['agentcompany']);
				$sheet->setCellValueByColumnAndRow(13, $row, $vo['biddercompany']);
				$sheet->setCellValueByColumnAndRow(14, $row, $vo['noticetime']?date('Y-m-d', $vo['noticetime']):'');
				$sheet->setCellValueByColumnAndRow(15, $row, $vo['bidopentime']?date('Y-m-d', $vo['bidopentime']):'');
				$sheet->setCellValueByColumnAndRow(16, $row, $vo['contracttime']?date('Y-m-d', $vo['contracttime']):'');
				$sheet->setCellValueByColumnAndRow(17, $row, $vo['bidding']?'附件':'');
				if($vo['bidding']) $sheet->getCellByColumnAndRow(17, $row)->getHyperlink()->setUrl($_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].$vo['bidding']);
				$sheet->setCellValueByColumnAndRow(18, $row, $vo['rfp']?'附件':'');
				if($vo['rfp']) $sheet->getCellByColumnAndRow(18, $row)->getHyperlink()->setUrl($_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].$vo['rfp']);
				$sheet->setCellValueByColumnAndRow(19, $row, $vo['acceptance']?'附件':'');
				if($vo['acceptance']) $sheet->getCellByColumnAndRow(19, $row)->getHyperlink()->setUrl($_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].$vo['acceptance']);
				$sheet->setCellValueByColumnAndRow(20, $row, $vo['lawyerletter']?'附件':'');
				if($vo['lawyerletter']) $sheet->getCellByColumnAndRow(20, $row)->getHyperlink()->setUrl($_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].$vo['lawyerletter']);
				$sheet->setCellValueByColumnAndRow(21, $row, $vo['contract']?'附件':'');
				if($vo['contract']) $sheet->getCellByColumnAndRow(21, $row)->getHyperlink()->setUrl($_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].$vo['contract']);
				$sheet->setCellValueByColumnAndRow(22, $row, $vo['totalmoney']);
				$sheet->setCellValueByColumnAndRow(23, $row, $vo['biddermoney']);
				$sheet->setCellValueByColumnAndRow(24, $row, $vo['execute_rate']);
				$sheet->setCellValueByColumnAndRow(25, $row, $vo['paymenttimes']);
				$sheet->setCellValueByColumnAndRow(26, $row, count($vo['payments']));
				$sheet->setCellValueByColumnAndRow(27, $row, $vo['fundingsource']);
				$sheet->setCellValueByColumnAndRow(28, $row, $vo['checkreport']?'附件':'');
				if($vo['checkreport']) $sheet->getCellByColumnAndRow(28, $row)->getHyperlink()->setUrl($_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].$vo['checkreport']);
				$sheet->setCellValueByColumnAndRow(29, $row, $vo['checktime']?date('Y-m-d', $vo['checktime']):'');
				$sheet->setCellValueByColumnAndRow(30, $row, $vo['warranty_period']);
				$sheet->setCellValueByColumnAndRow(31, $row, $vo['supervision_depart']);
				$sheet->setCellValueByColumnAndRow(32, $row, $vo['supervision_report']?'附件':'');
				if($vo['supervision_report']) $sheet->getCellByColumnAndRow(32, $row)->getHyperlink()->setUrl($_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].$vo['supervision_report']);
				$sheet->setCellValueByColumnAndRow(33, $row, $vo['audit_depart']);
				$sheet->setCellValueByColumnAndRow(34, $row, $vo['audit_report']?'附件':'');
				if($vo['audit_report']) $sheet->getCellByColumnAndRow(34, $row)->getHyperlink()->setUrl($_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].$vo['audit_report']);
				$sheet->setCellValueByColumnAndRow(35, $row, $vo['status']==0?'未开始':($vo['status']==1?'采购中':($vo['status']==2?'实施中':'项目完成')));
				$sheet->setCellValueByColumnAndRow(36, $row, $vo['admin']['nickname']);
			}
			
			$spreadsheet->createSheet();
			$spreadsheet->setActiveSheetIndex(1);
			$sheet = $spreadsheet->getActiveSheet()->setTitle('付款列表');
			$sheet->getStyle('A1:H1')->getFont()->setBold(true);
			$sheet->getCell('A1')->setValue('序号');
			$sheet->getCell('B1')->setValue('项目名称');
			$sheet->getCell('C1')->setValue('支付次数');
			$sheet->getCell('D1')->setValue('支付时间');
			$sheet->getCell('E1')->setValue('支付金额');
			$sheet->getCell('F1')->setValue('是否付款');
			$sheet->getCell('G1')->setValue('支付比例');
			//$sheet->getCell('H1')->setValue('累计比例');
			$sheet->getCell('H1')->setValue('支付条件');
			
			$list = $this->model->with(['payments'])->where($where)->order($sort, $order)->select();
			$i = 2;
			foreach($list as $project)
			{
				$leiji_paymentmoney = 0;
				foreach($project->payments as $key=>$vo)
				{
					$leiji_paymentmoney += $vo['paymentmoney'];
					
					$sheet->setCellValueByColumnAndRow(1, $i, $i-1);
					$sheet->setCellValueByColumnAndRow(2, $i, $project['name']);
					$sheet->setCellValueByColumnAndRow(3, $i, '第'.($key+1).'次付款');
					$sheet->setCellValueByColumnAndRow(4, $i, date('Y-m-d', $vo['paymenttime']));
					$sheet->setCellValueByColumnAndRow(5, $i, $vo['paymentmoney']);
					$sheet->setCellValueByColumnAndRow(6, $i, $vo['paymentstatus']==1?'已支付':'未支付');
					$sheet->setCellValueByColumnAndRow(7, $i, ($project['biddermoney']!=0?round($vo['paymentmoney']*100/$project['biddermoney'], 2):0).'%');
					//$sheet->setCellValueByColumnAndRow(8, $i, ($project['biddermoney']!=0?round($leiji_paymentmoney*100/$project['biddermoney'], 2):0).'%');
					$sheet->setCellValueByColumnAndRow(8, $i, $vo['paymentcondition']);
				
					$i++;
				}
			} */
			
			/* $payments = $this->paymentModel->with(['project'])->order('project_id desc, id asc')->select();
			$project_id = 0;
			$leiji_paymentmoney = 0;
			foreach($payments as $key=>$vo)
			{
				$sheet->setCellValueByColumnAndRow(1, $key+2, $key+1);
				$sheet->setCellValueByColumnAndRow(2, $key+2, $vo['project']['name']);
				
				if($project_id != $vo['project_id'])
				{
					$i = 1;
					$leiji_paymentmoney = 0;
					$project_id = $vo['project_id'];
				}
				$sheet->setCellValueByColumnAndRow(3, $key+2, '第'.$i.'次付款');
				$i++;
				$leiji_paymentmoney += $vo['paymentmoney'];
				
				$sheet->setCellValueByColumnAndRow(4, $key+2, date('Y-m-d', $vo['paymenttime']));
				$sheet->setCellValueByColumnAndRow(5, $key+2, $vo['paymentmoney']);
				$sheet->setCellValueByColumnAndRow(6, $key+2, $vo['paymentstatus']==1?'已支付':'未支付');
				$sheet->setCellValueByColumnAndRow(7, $key+2, round($vo['paymentmoney']*100/$vo['project']['biddermoney'], 2).'%');
				$sheet->setCellValueByColumnAndRow(8, $key+2, round($leiji_paymentmoney*100/$vo['project']['biddermoney'], 2).'%');
				$sheet->setCellValueByColumnAndRow(9, $key+2, $vo['paymentcondition']);
			} */
			
			/* $spreadsheet->setActiveSheetIndex(0);
			
			$filename = '项目列表';
			// MIME 协议，文件的类型，不设置，会默认html
			header('Content-Type:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
			// MIME 协议的扩展
			header('Content-Disposition:attachment;filename='.$filename.'.xlsx');
			// 缓存控制
			header('Cache-Control:max-age=0');
			
			$writer = new Wxlsx($spreadsheet);
			$writer->save('php://output');
		} catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
	} */
	
	public function departlist()
	{
		$departList = AdminDepart::column('id,pid,name');
		
        $departName = [];
        foreach ($departList as $k => $v) {
            $departName[$v['name']] = $v['name'];
        }
		return $departName;
	}
	

    /**
     * 添加
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
			$this->view->assign('departList', build_select('row[procuredepart]', $this->departdata, [], ['class'=>'form-control selectpicker', 'data-rule'=>'required']));
            return $this->view->fetch();
        }
		
		$this->token();
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $result = false;
        Db::startTrans();
        try {
			if($params['procuretype']==1||$params['procuretype']==2||$params['procuretype']==3||$params['procuretype']==4||$params['procuretype']==5||$params['procuretype']==6||$params['procuretype']==8)
			{
				if($params['checkstatus'])
				{
					$params['status'] = 3;
				}
				elseif(!empty($params['contract']) || isset($params['nocontract']))
				{
					$params['status'] = 2;
				}
				elseif(!empty($params['agentcompany']))
				{
					$params['status'] = 1;
				}
				else
				{
					$params['status'] = 0;
				}
			}
			elseif($params['procuretype']==7)
			{
				if($params['checkstatus'])
				{
					$params['status'] = 3;
				}
				elseif(!empty($params['contract']) || isset($params['nocontract']))
				{
					$params['status'] = 2;
				}
				else
				{
					$params['status'] = 1;
				}
			}
			else
			{
				$params['status'] = 0;
			}
			
			$params['totalmoney'] = str_replace(',', '', $params['totalmoney']);
			$params['biddermoney'] = str_replace(',', '', $params['biddermoney']);
			$params['admin_id'] = $this->auth->id;
            $result = $this->model->allowField(true)->save($params);
			if($params['paymenttimes'] && $result)
			{
				$payments = [];
				for($i=1; $i<=$params['paymenttimes']; $i++)
				{
					$payment = array(
						'project_id' => $this->model->id,
						'paymenttime' => $params['paymentimes-'.$i]['paymenttime'],
						'realpaymenttime' => $params['paymentimes-'.$i]['realpaymenttime'],
						'paymentmoney' => str_replace(',', '', $params['paymentimes-'.$i]['paymentmoney']),
						'paymentstatus' => $params['paymentimes-'.$i]['paymentstatus'],
						'paymentcondition' => $params['paymentimes-'.$i]['paymentcondition'],
					);
					$payments[] = $payment;
				}
				$this->paymentModel->allowField(true)->saveAll($payments);
			}
			
			//最近一次付款时间
			$lastpayment = $this->paymentModel->where(['project_id'=>$this->model->id, 'paymentstatus'=>1])->order('realpaymenttime', 'desc')->find();
			if($lastpayment)
			{
				$this->model->save(['lastpaymenttime'=>$lastpayment['realpaymenttime']]);
			}
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success('添加成功', 'index');
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
		$row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if (false === $this->request->isPost()) {
			
			if($row['paymenttimes'])
			{
				$payments = $this->paymentModel->where('project_id', $row['id'])->limit($row['paymenttimes'])->order('id', 'asc')->select();
				$leiji_paymentmoney = 0;
				foreach($payments as $key=>$vo)
				{
					if($vo['paymentmoney'] && $vo['paymentstatus']==1)
					{
						$leiji_paymentmoney += $vo['paymentmoney'];
						$vo['leiji_payment_rate'] = ($row['biddermoney']!=0?round($leiji_paymentmoney*100/$row['biddermoney'], 2):'0').'%';
					}
					
					$row['paymentimes-'.($key+1)] = $vo;
				}
				$row['execute_rate'] = ($row['biddermoney']!=0?round($leiji_paymentmoney*100/$row['biddermoney'], 2):'0').'%';
			}

			$this->view->assign('departList', build_select('row[procuredepart]', $this->departdata, $row['procuredepart'], ['class'=>'form-control selectpicker', 'data-rule'=>'required']));
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
		
		$this->token();
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
		
        $result = false;
        Db::startTrans();
        try {
			if($params['procuretype']==1||$params['procuretype']==2||$params['procuretype']==3||$params['procuretype']==4||$params['procuretype']==5||$params['procuretype']==6||$params['procuretype']==8)
			{
				if($params['checkstatus'])
				{
					$params['status'] = 3;
				}
				elseif(!empty($params['contract']) || isset($params['nocontract']))
				{
					$params['status'] = 2;
				}
				elseif(!empty($params['agentcompany']))
				{
					$params['status'] = 1;
				}
				else
				{
					$params['status'] = 0;
				}
			}
			elseif($params['procuretype']==7)
			{
				if($params['checkstatus'])
				{
					$params['status'] = 3;
				}
				elseif(!empty($params['contract']) || isset($params['nocontract']))
				{
					$params['status'] = 2;
				}
				else
				{
					$params['status'] = 1;
				}
			}
			else
			{
				$params['status'] = 0;
			}
			
			$params['nobidding'] = isset($params['nobidding'])?1:0;
			$params['norfp'] = isset($params['norfp'])?1:0;
			$params['noacceptance'] = isset($params['noacceptance'])?1:0;
			$params['nolawyerletter'] = isset($params['nolawyerletter'])?1:0;
			$params['nocontract'] = isset($params['nocontract'])?1:0;
			$params['supervise'] = isset($params['supervise'])?1:0;
			$params['nocheckreport'] = isset($params['nocheckreport'])?1:0;
			$params['nosupervision_report'] = isset($params['nosupervision_report'])?1:0;
			$params['noaudit_report'] = isset($params['noaudit_report'])?1:0;
			
			$old_paymenttimes = $row['paymenttimes'];
			
			$params['totalmoney'] = str_replace(',', '', $params['totalmoney']);
			$params['biddermoney'] = str_replace(',', '', $params['biddermoney']);
            $result = $row->allowField(true)->save($params);
			if($params['paymenttimes'] && $result)
			{
				$payments = [];
				for($i=1; $i<=$params['paymenttimes']; $i++)
				{
					$payment = array(
						'project_id' => $row->id,
						'paymenttime' => $params['paymentimes-'.$i]['paymenttime'],
						'realpaymenttime' => $params['paymentimes-'.$i]['realpaymenttime'],
						'paymentmoney' => str_replace(',', '', $params['paymentimes-'.$i]['paymentmoney']),
						'paymentstatus' => $params['paymentimes-'.$i]['paymentstatus'],
						'paymentcondition' => $params['paymentimes-'.$i]['paymentcondition'],
					);
					if($params['paymentimes-'.$i]['id']) $payment['id'] = $params['paymentimes-'.$i]['id'];
					$payments[] = $payment;
				}
				$this->paymentModel->allowField(true)->saveAll($payments);
				
				if($old_paymenttimes>$params['paymenttimes'])
				{
					$delete_ids = array_column($payments, 'id');
					$this->paymentModel->where('project_id', $row['id'])->where('id', 'not in', $delete_ids)->delete();
				}
			}
			
			//最近一次付款时间
			$lastpayment = $this->paymentModel->where(['project_id'=>$row->id, 'paymentstatus'=>1])->order('realpaymenttime', 'desc')->find();
			if($lastpayment)
			{
				$row->save(['lastpaymenttime'=>$lastpayment['realpaymenttime']]);
			}
			else
			{
				$row->save(['lastpaymenttime'=>0]);
			}
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
	
	/**
     * 补充
     */
    public function supple($ids = null)
    {
		$row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if (false === $this->request->isPost()) {
			$field = $this->request->get('field');
			
			$this->view->assign('field', $field);
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
		
		$this->token();
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
		
        $result = false;
        Db::startTrans();
        try {
			if($row['procuretype']==1||$row['procuretype']==2||$row['procuretype']==3||$row['procuretype']==4||$row['procuretype']==5||$row['procuretype']==6||$row['procuretype']==8)
			{
				if($row['checkstatus'])
				{
					$params['status'] = 3;
				}
				elseif(!empty($params['contract']) || isset($params['nocontract']))
				{
					$params['status'] = 2;
				}
				elseif(!empty($params['agentcompany']))
				{
					$params['status'] = 1;
				}
				else
				{
					$params['status'] = 0;
				}
			}
			elseif($row['procuretype']==7)
			{
				if($row['checkstatus'])
				{
					$params['status'] = 3;
				}
				elseif(!empty($params['contract']) || isset($params['nocontract']))
				{
					$params['status'] = 2;
				}
				else
				{
					$params['status'] = 1;
				}
			}
			else
			{
				$params['status'] = 0;
			}
			
			$params['nobidding'] = isset($params['nobidding'])?1:0;
			$params['norfp'] = isset($params['norfp'])?1:0;
			$params['noacceptance'] = isset($params['noacceptance'])?1:0;
			$params['nolawyerletter'] = isset($params['nolawyerletter'])?1:0;
			$params['nocontract'] = isset($params['nocontract'])?1:0;
						
            $result = $row->allowField(true)->save($params);

            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
	
	/**
     * 付款
     */
    public function pay($ids = null)
    {
		$row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if (false === $this->request->isPost()) {
			
			if($row['paymenttimes'])
			{
				$payments = $this->paymentModel->where('project_id', $row['id'])->limit($row['paymenttimes'])->order('id', 'asc')->select();
				$leiji_paymentmoney = 0;
				foreach($payments as $key=>$vo)
				{
					if($vo['paymentmoney'] && $vo['paymentstatus']==1)
					{
						$leiji_paymentmoney += $vo['paymentmoney'];
						$vo['leiji_payment_rate'] = ($row['biddermoney']!=0?round($leiji_paymentmoney*100/$row['biddermoney'], 2):'0').'%';
					}
					
					$row['paymentimes-'.($key+1)] = $vo;
				}
				$row['execute_rate'] = ($row['biddermoney']!=0?round($leiji_paymentmoney*100/$row['biddermoney'], 2):'0').'%';
			}

            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
		
		$this->token();
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
		
        $result = false;
        Db::startTrans();
        try {
			$old_paymenttimes = $row['paymenttimes'];
			
			$params['totalmoney'] = str_replace(',', '', $params['totalmoney']);
			$params['biddermoney'] = str_replace(',', '', $params['biddermoney']);
            $result = $row->allowField(true)->save($params);
			if($params['paymenttimes'] && $result)
			{
				$payments = [];
				for($i=1; $i<=$params['paymenttimes']; $i++)
				{
					$payment = array(
						'project_id' => $row->id,
						'paymenttime' => $params['paymentimes-'.$i]['paymenttime'],
						'realpaymenttime' => $params['paymentimes-'.$i]['realpaymenttime'],
						'paymentmoney' => str_replace(',', '', $params['paymentimes-'.$i]['paymentmoney']),
						'paymentstatus' => $params['paymentimes-'.$i]['paymentstatus'],
						'paymentcondition' => $params['paymentimes-'.$i]['paymentcondition'],
					);
					if($params['paymentimes-'.$i]['id']) $payment['id'] = $params['paymentimes-'.$i]['id'];
					$payments[] = $payment;
				}
				$this->paymentModel->allowField(true)->saveAll($payments);
				
				if($old_paymenttimes>$params['paymenttimes'])
				{
					$delete_ids = array_column($payments, 'id');
					$this->paymentModel->where('project_id', $row['id'])->where('id', 'not in', $delete_ids)->delete();
				}
			}
			
			//最近一次付款时间
			$lastpayment = $this->paymentModel->where(['project_id'=>$row->id, 'paymentstatus'=>1])->order('realpaymenttime', 'desc')->find();
			if($lastpayment)
			{
				$row->save(['lastpaymenttime'=>$lastpayment['realpaymenttime']]);
			}
			else
			{
				$row->save(['lastpaymenttime'=>0]);
			}
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
	
	public function paymentview($ids = null)
	{
		$row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
		$payments = $this->paymentModel->where('project_id', $row['id'])->limit($row['paymenttimes'])->order('id', 'asc')->select();
		foreach($payments as &$vo)
		{
			$vo['paymentrate'] = ($row['biddermoney']!=0?round($vo['paymentmoney']*100/$row['biddermoney'], 2):'0').'%';
		}
		$row['payments'] = $payments;
		$this->view->assign('row', $row);
        return $this->view->fetch();
	}
	
	public function view($ids = null)
	{
		$row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
		$content = '';
		if($row['status'] == 0)
		{
			$content = '该项目还未开始';
		}
		elseif($row['status'] == 1)
		{
			$uncomplete = '';
			if($row['agentcompany'] == '')
			{
				$uncomplete .= '代理公司，';
			}
			if($row['biddercompany'] == '')
			{
				$uncomplete .= '中标单位，';
			}
			if($row['noticetime'] == 0)
			{
				$uncomplete .= '公告发布时间，';
			}
			if($row['bidopentime'] == 0)
			{
				$uncomplete .= '开标时间，';
			}
			if($row['contracttime'] == 0)
			{
				$uncomplete .= '合同签订时间，';
			}
			if($row['bidding'] == '' && $row['nobidding'] == 0)
			{
				$uncomplete .= '招标文件，';
			}
			if($row['rfp'] == '' && $row['norfp'] == 0)
			{
				$uncomplete .= '投标文件，';
			}
			if($row['acceptance'] == '' && $row['noacceptance'] == 0)
			{
				$uncomplete .= '中标通知书，';
			}
			if($row['contract'] == '' && $row['nocontract'] == 0)
			{
				$uncomplete .= '中标合同，';
			}
			if($row['lawyerletter'] == '' && $row['nolawyerletter'] == 0)
			{
				$uncomplete .= '律师审核意见书';
			}
			$content = '该项目已进入到采购中状态，其中还有'.trim($uncomplete, '，').'未填写可尽快填写！';
		}
		elseif($row['status'] == 2)
		{
			$content = '该项目已进入到实施中状态，';
			
			$uncomplete = '';
			if($row['bidding'] == '' && $row['nobidding'] == 0)
			{
				$uncomplete .= '招标文件，';
			}
			if($row['rfp'] == '' && $row['norfp'] == 0)
			{
				$uncomplete .= '投标文件，';
			}
			if($row['acceptance'] == '' && $row['noacceptance'] == 0)
			{
				$uncomplete .= '中标通知书，';
			}
			if($row['contract'] == '' && $row['nocontract'] == 0)
			{
				$uncomplete .= '中标合同，';
			}
			if($row['lawyerletter'] == '' && $row['nolawyerletter'] == 0)
			{
				$uncomplete .= '律师审核意见书';
			}
			if($uncomplete)
			{
				$content .= '但'.trim($uncomplete, '，').'未上传，';
			}
			
			$payments = $this->paymentModel->where('project_id', $row['id'])->limit($row['paymenttimes'])->order('id', 'asc')->select();
			$leiji_paymentmoney = 0;
			$paymentconditions = '';
			$nextpaymenttime = '';
			foreach($payments as $key=>$vo)
			{
				if($vo['paymentmoney'] && $vo['paymentstatus']==1)
				{
					$leiji_paymentmoney += $vo['paymentmoney'];
				}
				
				if(empty($vo['paymentcondition']))
				{
					$paymentconditions .= '第'.($key+1).'次、';
				}
				
				if($vo['paymentstatus']==0 && $nextpaymenttime == '')
				{
					$nextpaymenttime = $vo['paymenttime']?date('Y年m月d日', $vo['paymenttime']):'未填写';
				}
			}
			$row['execute_rate'] = ($row['biddermoney']!=0?round($leiji_paymentmoney*100/$row['biddermoney'], 2):'0').'%';
			$content .= '合同金额为'.$row['biddermoney'].'，';
			if(empty($row['fundingsource']))
			{
				$content .= '资金来源未注明，';
			}
			$content .= '已支付'.$leiji_paymentmoney.'，  支付比例为'.$row['execute_rate'];
			
			if($paymentconditions)
			{
				$content .= '，'.trim($paymentconditions, '、').'支付条件未注明';
			}
			
			if($nextpaymenttime)
			{
				$content .= '，'.'下次付款时间'.$nextpaymenttime;
			}
		}
		else
		{
			$content = '该项目已完成';
		}
		
		$this->view->assign('content', $content);
        return $this->view->fetch();
	}

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
		if (!$ids) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $count = $this->model->where('id', 'in', $ids)->delete();
		if ($count) {
			$this->paymentModel->where('project_id', 'in', $ids)->delete();
			$this->success();
		}

        $this->error(__('No rows were deleted'));
    }

	/**
     * 续费
     */
    public function renew($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
		if (!$ids) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $list = $this->model->where('id', 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                $data = array(
					'serialnumber' => $item->serialnumber,
					'budgetyear' => $item->budgetyear,
					'name' => $item->name,
					'starttime' => $item->starttime,
					'shishitime' => $item->shishitime,
					'endtime' => $item->endtime,
					'procuredepart' => $item->procuredepart,
					'procuretype' => $item->procuretype,
					'biddercompany' => $item->biddercompany,
					'agentcompany' => $item->agentcompany,
					'noticetime' => $item->noticetime,
					'bidopentime' => $item->bidopentime,
					'contracttime' => $item->contracttime,
					'contacter' => $item->contacter,
					'contactphone' => $item->contactphone,
					'totalmoney' => $item->totalmoney,
					'biddermoney' => $item->biddermoney,
					'paymenttimes' => $item->paymenttimes,
					'lastpaymenttime' => $item->lastpaymenttime,
					'fundingsource' => $item->fundingsource,
					'rfp' => $item->rfp,
					'norfp' => $item->norfp,
					'acceptance' => $item->acceptance,
					'noacceptance' => $item->noacceptance,
					'checkreport' => $item->checkreport,
					'checkstatus' => $item->checkstatus,
					'checktime' => $item->checktime,
					'supervise' => $item->supervise,
					'warranty_period' => $item->warranty_period,
					'supervision_depart' => $item->supervision_depart,
					'supervision_report' => $item->supervision_report,
					'audit_depart' => $item->audit_depart,
					'audit_report' => $item->audit_report,
					'lawyerletter' => $item->lawyerletter,
					'nolawyerletter' => $item->nolawyerletter,
					'bidding' => $item->bidding,
					'nobidding' => $item->nobidding,
					'contract' => $item->contract,
					'nocontract' => $item->nocontract,
					'nocheckreport' => $item->nocheckreport,
					'nosupervision_report' => $item->nosupervision_report,
					'noaudit_report' => $item->noaudit_report,
					'status' => $item->status,
					'admin_id' => $this->auth->id,
				);
				$project = ProjectModel::create($data);
				
				$payments = $this->paymentModel->where('project_id', $item->id)->select();
				$insertPayments = [];
				foreach($payments as $vo)
				{
					$data = array(
						'project_id' => $project->id,
						'paymenttime' => $vo->paymenttime,
						'realpaymenttime' => $vo->realpaymenttime,
						'paymentmoney' => $vo->paymentmoney,
						'paymentstatus' => $vo->paymentstatus,
						'paymentcondition' => $vo->paymentcondition
					);
					$insertPayments[] = $data;
				}
				$this->paymentModel->saveAll($insertPayments);
				
				$count++;
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were renewed'));
    }
}
